import { BookTwoTone, DeleteOutlined, EditOutlined, PlayCircleTwoTone, PlusOutlined } from '@ant-design/icons'
import type { ActionType, ProColumns } from '@ant-design/pro-components'
import { PageContainer, ProTable } from '@ant-design/pro-components'
import { Button, Popconfirm, Progress, Tree, TreeDataNode, message } from 'antd'
const { DirectoryTree } = Tree
import { useEffect, useState, useRef } from 'react'

import { queryCatalogTree } from '@/services/study/catalog'
import { StudyContentItem, StudyContentParams, StudyContentReq, addUpdate, queryList, remove, start, updateProgress } from '@/services/study/content'
import StudyContentForm from './studyContentForm'
import UpdateContentForm from './updateContentForm'

export default () => {
  const [key, setKey] = useState(0)
  const [catalogTree, setCatalogTree] = useState<TreeDataNode[]|undefined>()
  const [open, setOpen] = useState<boolean>(false)
  const [updateOpen, setUpdateOpen] = useState<boolean>(false)
  const [studyContentItem, setStudyContentItem] = useState<Partial<StudyContentItem> | undefined>()
  const [studyContentReq, setStudyContentReq] = useState<Partial<StudyContentReq> | undefined>()
  const actionRef = useRef<ActionType>()

  useEffect(() => {
    queryCatalogTree().then(res =>{
      setCatalogTree(res.data)
    })
  }, [])

  /**
   * 添加编辑内容
   * @param fields
  */
  const handleSubmit = async (fields: StudyContentItem) => {
    setOpen(false)
    const msg = fields.id ? '编辑' : '添加'
    message.loading('正在' + msg + '内容')
    const res = await addUpdate({ ...fields })

    if (res.success) {
      message.success(msg + '内容成功')
      if (actionRef.current) {
        actionRef.current.reload()
      }
    } else {
      message.error(res.msg)
    }
  }

  /**
   * 添加编辑内容
   * @param fields
  */
  const handleUpdate = async (fields: StudyContentReq) => {
    setUpdateOpen(false)
    message.loading('正在更新学习进度')
    const res = await updateProgress({ ...fields })

    if (res.success) {
      message.success('更新学习进度成功')
      if (actionRef.current) {
        actionRef.current.reload()
      }
    } else {
      message.error(res.msg)
    }
  }

  /**
   * 删除内容
   * @param item
   */
  const handleRemove = async (item: StudyContentItem) => {
    message.loading('正在删除 ' + item.name + ' 内容')
    const res = await remove(item.id)
    if (res.success) {
      message.success(item.name + '内容删除成功')
      if (actionRef.current) {
        actionRef.current.reload()
      }
    } else {
      message.error(res.msg)
    }
  }

  /**
   * 开始学习内容
   * @param item
   */
  const handleStart = async (item: StudyContentItem) => {
    message.loading('开始学习 ' + item.name + ' 内容')
    const res = await start(item.id)
    if (res.success) {
      message.success(item.name + '已开始学习')
      if (actionRef.current) {
        actionRef.current.reload()
      }
    } else {
      message.error(res.msg)
    }
  }

  const showAddModal = () => {
    if(0 == key){
      message.error("请选择栏目")
      return
    }else{
      setOpen(true)
      setStudyContentItem({ 
        optType: 'add',
        catalogId: key
      })
    }
  }

  const showEditModal = (item: StudyContentItem) => {
    setOpen(true)
    setStudyContentItem(item)
  }

  const showUpdaModal = (item: StudyContentItem) => {
    setUpdateOpen(true)
    setStudyContentReq(item)
  }

  const columns: ProColumns<StudyContentItem>[] = [
    {
      title: '目录名称',
      dataIndex: 'catalogName',
      width: 150,
      search: false,
    },
    {
      title: '类型',
      dataIndex: 'type',
      ellipsis: true,
      valueEnum: {
        'E': {
          text: '电子书',
        },
        'B': {
          text: '书箱',
        },
        'V': {
          text: '视频',
        },
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      search: false,
      render: (_, record) => (
        <div
          title={`${record.resource}`}
        >
          {record.name}
        </div>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      search: false,
      ellipsis: true,
      render: (_, record) => (
        <div
          title={`${record.translator ? (record.translator) + ' 译' : ''}`}
        >
          {record.author}
        </div>
      ),
    },
    {
      title: '进度',
      dataIndex: 'publisher',
      search: false,
      render: (_, record) => (
        <div
          title={`${record.doneIndex}/${record.targetIndex} - ${record.studyDays ? '已学 ' + (record.studyDays) + '天' : '未开始 '}`}
        >
        <Progress
          percent={record.currentProgress}
          size="small"
          steps={20}
          status={
            record.currentProgress > 100
              ? 'exception'
              : record.currentProgress > 99
              ? 'success'
              : 'normal'
          }
        /> 
        </div>
      ),
    },
    {
      title: '来源',
      dataIndex: 'resource',
      search: false,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        '0': {
          text: '学习中',
          status: 'Processing',
        },
        '1': {
          text: '待学习',
          status: 'Error',
        },
        '2': {
          text: '已学习',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 90,
      render: (_, record)  => [
        <a
          key="edit"
          onClick={() => showEditModal({ ...record, optType: 'edit' })}
          hidden={'1' != record.status}
          title="编辑内容"
        >
          <EditOutlined />
        </a>,
        <Popconfirm title="是否要删除此目录？" onConfirm={() => handleRemove(record)}>
          <a key="delete" title="删除目录" hidden={'1' != record.status}>
            <DeleteOutlined />
          </a>
        </Popconfirm>,
        <a 
          key="start"
          onClick={() => handleStart(record)}
          hidden={'0' == record.status}
          title="开始学习"
        >
          <PlayCircleTwoTone />
        </a>,
        <a 
          key="update"
          onClick={() => showUpdaModal({ ...record })}
          hidden={'0' != record.status}
          title="更新学习进度"
        >
          <BookTwoTone />
        </a>,
      ],
    },
  ]

  return (
    <PageContainer title={false}>
      <ProTable<StudyContentItem>
        columns={columns}
        rowKey="key"
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              showAddModal()
            }}
            title="添加内容"
            type="primary">
          </Button>
        ]}
        pagination={{
          pageSize: 10
        }}
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            <DirectoryTree
              showLine
              style={{ width: 180 }}
              defaultExpandAll
              onSelect={(e)=>{
                setKey(e[0] as number)
              }}
              treeData={ catalogTree }
            />
            <div
              style={{
                width: 1
              }}
            />
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        params={{
          key,
        }}
        request={ (params) => {
          return queryList({...params, catalogId: key} as StudyContentParams)
        }}
      />
      <StudyContentForm
        studyContentItem={studyContentItem}
        open={open}
        onCancel={() => setOpen(false)}
        onSubmit={handleSubmit}
      />
      <UpdateContentForm
        studyContentReq={studyContentReq}
        open={updateOpen}
        onCancel={() => setUpdateOpen(false)}
        onSubmit={handleUpdate}
      />
    </PageContainer>
  )
}